package com.admins.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author mis_wu
 * @date 2022/4/7 20:40
 * 全局日志 切面类
 */
@Aspect
@Component
@Slf4j
public class WebLogAspect {

    /**
     * 切入点
     * .* 前面包下所有的类
     * .* 类中所有方法
     * (..)方法中所有参数
     */
    @Pointcut("execution(public * com.admins.service.impl.*.*(..))")
    public void webLog(){}

    /**
     * 前置增强
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        //接收到请求
        ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //记录
        log.info("URL: {}",request.getRequestURL().toString());
        log.info("Http_Method: {}",request.getMethod());
        log.info("IP: {}",request.getRemoteAddr());
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            log.info("name: {}, value: {}",name,request.getParameter(name));
        }
    }

    /**
     * 目标方法请求之后的信息
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable{
        //处理完请求返回内容
        log.info("Response Data: {}",ret);
    }
}
